package com.kylin.common.security.util;

import com.alibaba.fastjson2.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kylin.common.core.beans.ResultBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * Response工具类
 * @author wuhao
 * @version 1.0 - 2022/8/15
 */
public class ResponseUtils {

    public static void out(HttpServletResponse response, ResultBean<Serializable> result) {
        ObjectMapper mapper = new ObjectMapper();
        PrintWriter writer = null;
        response.setCharacterEncoding("utf-8");
        response.setStatus(HttpStatus.OK.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        try {
            writer = response.getWriter();
            String resultStr = JSON.toJSONString(result);
            System.out.println(resultStr);
            mapper.writeValue(writer, JSON.parseObject(resultStr));
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.flush();
                writer.close();
            }
        }
    }
}
